/**
 * 
 */
package com.tvshows.structure.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.tvshows.ObjectFactory;
import com.tvshows.Schedule;
import com.tvshows.Show;
import com.tvshows.Shows;
import com.tvshows.structure.beans.Favorite;

/**
 * @author tMidy
 * <p>
 * Class that exports/imports xml files with shows data
 * </p>
 */
public final class XmlExporter
{

    /**
     * private constructor
     */
    private XmlExporter()
    {

    }

    /**
     * export the xml file to the specified path
     * 
     * @param favorites the list to export
     * @param path the path to export
     * @throws JAXBException
     * @throws IOException
     */
    public static void exportToXml( List<Favorite> favorites, String path )
        throws JAXBException, IOException
    {
        JAXBContext jc = JAXBContext.newInstance( "com.tvshows" );
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
        Shows shows = new ObjectFactory().createShows();

        for ( Favorite favorite : favorites )
        {
            Show show = new Show();
            show.setEpisode( favorite.getLastEpisodeNumber() );
            show.setSeason( favorite.getSeasonNumber() );
            show.setName( favorite.getNameFavorite() );
            if ( favorite.getScheduleFavorite() != null )
            {
                show.setSchedule( Schedule.fromValue( favorite.getScheduleFavorite() ) );
            }
            shows.getShow().add( show );

        }
        marshaller.marshal( shows, new FileWriter( new File( path ) ) );
    }

    /**
     * @param path the file to import
     * @return the imported favoriteList
     * @throws JAXBException
     */
    public static List<Favorite> retreiveImportList( String path )
        throws JAXBException
    {
        JAXBContext jc = JAXBContext.newInstance( "com.tvshows" );
        Unmarshaller unMarshaller = jc.createUnmarshaller();

        Shows shows = (Shows) unMarshaller.unmarshal( new File( path ) );
        List<Favorite> favorites = new ArrayList<Favorite>();

        for ( Show show : shows.getShow() )
        {
            Favorite favorite = new Favorite();
            favorite.setLastEpisodeNumber( show.getEpisode() );
            favorite.setSeasonNumber( show.getSeason() );
            favorite.setNameFavorite( show.getName() );
            favorite.setScheduleFavorite( show.getSchedule().toString() );
            favorites.add( favorite );
        }
        return favorites;
    }
}
